package rabbitmq.work;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    //先启动两个消费者，否则可能造成其中一个消费者一条消息都拿不到
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);//需要提前开放端口号
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        //2. 建立信道
        Channel channel = connection.createChannel();
        //3. 声明队列 使用内置交换机
        //队列不存在则创建，存在则不创建
        channel.queueDeclare(Constants.WORK_QUEUE,true,false,false,null);
        //4. 发送消息
        for (int i = 0; i < 10; i++) {
            String msg = "hello work queue..."+i;
            channel.basicPublish("",Constants.WORK_QUEUE,null,msg.getBytes());
        }
        System.out.println("消息发送成功");
        //6. 进行资源的释放（释放连接与信道）
        channel.close();
        connection.close();

    }
}
